<template>
  <div class="page-container">
    <!-- 快捷操作 -->
    <ListQuickNavigation ref="listQuickNavigationRef" @change="quickNavigationChange" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" @reset="handleReset" />
    <!-- 表格 -->
    <table-index :table="table" @loadData="loadData">
      <template #carModal="{ record }">
        <div class="info-item">
          <div>【车型】</div>
          <div>{{ record.modelName }}</div>
        </div>
        <div class="mt-2 info-item">
          <div>【价格模板】</div>
          <div>{{ record.templateName }}</div>
        </div>
      </template>
      <template #site="{ record }">
        <div class="info-item">
          <span class="mr-1 site-num-val">{{ record.siteCount }}</span>
          <a-button type="outline" size="mini" @click="openSiteDetail(record)">查看</a-button>
        </div>
      </template>
      <template #priceInfo="{ record }">
        <div
          class="info-item"
          v-if="
            record.price || record.weekendPrice || record.poundageAmount || record.holidayInfoJson?.length || record.customInfoJson?.length
          "
        >
          <div v-if="record.price">平日价：{{ record.price }} 元/日</div>
          <div class="grid pt-4" v-if="record.weekendPrice">
            <div
              >周末价：<span class="whitespace-nowrap"> {{ record.weekendPrice }}元/日</span>
            </div>
            <a-space>
              <a-tag v-for="(item, index) in record.weekendDayList" color="blue" :key="index">
                {{ item == 5 ? '周五' : item == 6 ? '周六' : '周日' }}
              </a-tag>
            </a-space>
          </div>
          <div class="pt-4" v-if="record.poundageAmount">手续费：{{ record.poundageAmount }} 元/次</div>
          <div class="relative pt-4 pl-14" v-if="record.holidayInfoJson && record.holidayInfoJson.length">
            <div class="jr-label">节假日-</div>
            <div v-for="item in record.holidayInfoJson" :key="item.type"
              >{{ item.typeName }}： <span class="whitespace-nowrap"> {{ item.price }} 元/日</span>
            </div>
          </div>
          <div class="pt-4" v-if="record.customInfoJson && record.customInfoJson.length">
            <div>自定义价格：</div>
            <div v-for="(item, index) in record.customInfoJson" :key="index">
              {{ item.startTime }}至{{ item.endTime }} <span class="whitespace-nowrap"> {{ item.price }}元/日</span></div
            >
          </div>
        </div>
      </template>
      <!-- 反写对象 -->
      <template #sourceIdName="{ record }">
        <div v-for="item in record.channelList" :key="item.id">
          <div class="text-child">{{ item.sourceIdName }}: {{ item.username }}</div>
          <div class="td-divider" v-if="item.id != record.channelList.at(-1).id"></div>
        </div>
      </template>
      <!-- 反写结果 -->
      <template #statusName="{ record }">
        <div v-for="item in record.channelList" :key="item.id">
          <div class="text-child">
            <status-tag :value="item.status" :label="item.statusName" type="syncOtaPriceStatus" />
            <!-- <span :class="['res_status', 'res_status_' + item.status]">{{ item.statusName }}</span> -->
            <!-- // 0, "反写中"  1, "反写成功"  2, "部分失败"  -1, "反写失败" -->
            <a-button type="outline" size="mini" class="ml-1" @click="toDetail(item)">查看</a-button>
          </div>
          <div class="td-divider" v-if="item.id != record.channelList.at(-1).id"></div>
        </div>
      </template>
      <!-- 反写时间 -->
      <template #finishTime="{ record }">
        <div v-for="item in record.channelList" :key="item.id">
          <div class="text-child">{{ item.finishTime || '-' }}</div>
          <div class="td-divider" v-if="item.id != record.channelList.at(-1).id"></div>
        </div>
      </template>
      <!-- 操作人 -->
      <template #operatorUserName="{ record }">
        <div v-for="item in record.channelList" :key="item.id">
          <div class="text-child">{{ item.operatorUserName || '-' }}</div>
          <div class="td-divider" v-if="item.id != record.channelList.at(-1).id"></div>
        </div>
      </template>
      <!-- 操作 -->
      <template #operate="{ record }">
        <div v-for="item in record.channelList" :key="item.id">
          <div class="text-child">
            <a
              v-permission="'svms:business:channel:sync-ota-price.retrySyncOTA'"
              class="operate-button"
              v-if="item.status == 2 || item.status == -1"
              @click="retrySyncOTA(item)"
              >重新反写</a
            >
          </div>
          <div class="td-divider" v-if="item.id != record.channelList.at(-1).id"></div>
        </div>
      </template>
    </table-index>

    <!-- 详情 -->
    <DetailModal ref="detailModalRef" />
    <!-- 模板门店弹窗 -->
    <TemplateSiteModal ref="templateSiteModalRef" />
  </div>
</template>

<script setup name="SyncOtaPrice">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { usePageDict } from '@/hooks/useDict'
  import { getChannelSyncPriceList, retryChannelSyncPrice } from '@/api/business/channelSyncPrice'
  import ListQuickNavigation from './components/list-quick-navigation.vue'
  import DetailModal from './components/detail-modal.vue'
  import TemplateSiteModal from '../components/template-site-modal.vue'
  import { Modal, Message } from '@arco-design/web-vue'

  const dict = usePageDict('channelSyncPrice')
  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }

  // 定义 queryParam
  const queryParam = reactive({
    statusList: [],
    createTimeRange: [], // 发起时间
    payTimeRange: [], // 完成时间
    sortField: '',
    sortType: '',
  })
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车型', prop: 'modelIdList', type: 'remote-select', attrs: { type: 'car_model_tenantList_multiple' } },
      { label: '应用门店', prop: 'siteIdList', type: 'remote-select', attrs: { type: 'site_lease_list_multiple' } },
      { label: '车型价格模板名称', prop: 'templateIdList', type: 'remote-select', attrs: { type: 'multiple_tenantPriceTemplate' } },
      { label: '反写对象', prop: 'sourceIdList', type: 'a-select', options: dict.thirdpartySourceEnum, attrs: { multiple: true } },
      { label: '反写结果', prop: 'statusList', type: 'a-select', options: dict.statusEnum, attrs: { multiple: true } },
      { label: '操作人', prop: 'operatorNameLike', type: 'a-input' },
      {
        label: '发起反写时间',
        prop: 'createTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.createTimeStart = value[0]
          queryParam.createTimeEnd = value[1]
        },
      },
      {
        label: '完成反写时间',
        prop: 'payTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.finishTimeStart = value[0]
          queryParam.finishTimeEnd = value[1]
        },
      },
    ]
  })

  // table 配置
  const table = useTable({
    queryParam,
    columns: [
      {
        title: '发起反写时间',
        dataIndex: 'createTime',
        width: 180,
        fixed: 'left',
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
      },
      { title: '车型信息', slotName: 'carModal', width: 180 },
      { title: '应用门店', slotName: 'site', width: 110 },
      { title: '反写价格信息', slotName: 'priceInfo', width: 300 },
      { title: '反写对象', slotName: 'sourceIdName', width: 180 },
      { title: '反写结果', slotName: 'statusName', width: 150 },
      { title: '完成反写时间', slotName: 'finishTime', width: 180 },
      { title: '操作人', slotName: 'operatorUserName', width: 100 },
      { title: '操作', slotName: 'operate', width: 90, fixed: 'right' },
    ],
  })

  // 详情
  const detailModalRef = ref()
  const toDetail = (record) => {
    detailModalRef.value.open(record)
  }
  // 重新反写
  const retrySyncOTA = (record) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      content: '是否重新反写？',
      okText: '确认',
      onBeforeOk: async () => {
        const res = await retryChannelSyncPrice({ id: record.id })
        if (res.code == 200) {
          Message.success('重新反写成功')
          loadData(1)
        }
        return true
      },
    })
  }

  // 查看应用门店详情
  const templateSiteModalRef = ref()
  const openSiteDetail = (record) => {
    templateSiteModalRef.value.open(record.siteNameList)
  }

  const listQuickNavigationRef = ref()
  const loadData = (page) => {
    listQuickNavigationRef.value.init(queryParam)
    const fn = useFetchTableDataApi(table, queryParam, getChannelSyncPriceList)
    fn(page).then((res) => {
      // 过滤掉审批流程没有审批人的
      res.data.forEach((item) => {
        item.customInfoJson.forEach((it) => {
          it.startTime = it.startTime.slice(0, 10)
          it.endTime = it.endTime.slice(0, 10)
        })
      })
    })
  }

  // 快捷导航切换
  const quickNavigationChange = (param) => {
    // 清空
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    queryParam.statusList = param.statusList
    loadData(1)
  }
  // 快捷导航重置
  const handleReset = () => {
    listQuickNavigationRef.value.reset()
  }
  
  onMounted(() => {
    loadData(1)
  })
</script>

<style lang="less" scoped>
  .res_status {
    color: #f76964;
    &_0 {
      color: #1890ff;
    }
    &_1 {
      color: #00b42a;
    }
    &_2 {
      color: #ff7d00;
    }
  }

  .jr-label {
    position: absolute;
    left: 0;
    top: 16px;
  }

  .text-child {
    line-height: 20px;
    height: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 3;
    display: -webkit-box;
    -webkit-box-orient: vertical;

    display: flex;
    align-items: center;
  }

  .operate-button {
    min-width: 50%;
    display: inline-flex;
    align-items: center;
    line-height: 32px;
    white-space: nowrap;
    cursor: pointer;
    user-select: none;
    height: 32px;
    font-size: 14px;
    border-radius: var(--border-radius-small);
    color: rgb(var(--primary-6));
    &:hover {
      font-weight: 600;
    }
  }
</style>
